package com.xu.ReenterLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁(简单用法）
 *
 *  lock():获得锁 如果锁已经被占用  则等待
 *  lockInterruptibly() 获得锁  优先响应中断
 *  tryLock() 尝试获取锁，如果成功返回true  失败则返回  该方法不等待 立即返回
 *  unlock（）  释放锁
 *
 * @author xudenghui
 * @create 2021-10-12 14:34
 **/
public class ReenterLockDemo implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();

    public static int i = 0;


    public void run() {
        for (int j = 0; j < 10000000; j++) {
            lock.lock();
            try {
                i++;
            } finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReenterLockDemo t1 = new ReenterLockDemo();
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t1);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(i);

    }
}
